﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using widgetLoader.Properties;
using wdwp.Desktop.widgetLib.Utils;
using System.Runtime.InteropServices;


namespace wdwp.Desktop.Loader
{
    /// <summary>
    /// 위젯을 호스팅하는 창
    /// </summary>
    public partial class WidgetHostForm : Form
    {
        WidgetSettingsForm m_wndSettings;
        WidgetLoader m_widgetLoader;
        bool m_bTrackingMouse;

        int prevX;
        int prevY;

        int wndX;
        int wndY;
               
                
        public WidgetHostForm(WidgetLoader loaderBase)
        {           
            InitializeComponent();

            m_bTrackingMouse = false;
                        
                        
            //"위젯별 세팅"을 로드하여 위젯로더의 Application 설정과 동기화
            m_widgetLoader = loaderBase;

            prevX = 0;
            prevY = 0;

          
        }


        void Default_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Opacity")
            {
                this.Opacity = (Double)Settings.Default.Opacity / 10;
            }
            else if (e.PropertyName == "AlwaysOnTop")
            {
                this.SetTopLevel(Settings.Default.AlwaysOnTop);
                this.TransparencyKey = Color.Magenta;
            }
        }


        private void widgetHostForm_Load(object sender, EventArgs e)
        {
            try
            {
                //위젯 설정창 로드 
                m_wndSettings = new WidgetSettingsForm(this);

                if (m_widgetLoader.loadWdgtSettings(Settings.Default.LoaderStartupFileName) == true)
                {
                    //동기화가 정상적으로 이루어지면 이제부터 로더의 설정을 사용 
                    this.Top = Settings.Default.StartY;
                    this.Left = Settings.Default.StartX;
                    this.Width = Settings.Default.Width + 30;
                    this.Height = Settings.Default.Height + 30;

                    this.Opacity = ((double)Settings.Default.Opacity) / 10;
                    
                    //m_prevPoint = new Point(this.Left, this.Top);

                    //설정창 관련 
                    m_wndSettings.Top = this.Top;
                    m_wndSettings.Left = this.Left + this.Width;

                }
                else
                {
                    //설정에 문제가 있어 정상적인 로드가 안이루어 졌다면 다른처리
                }

                //위젯 로드
                Uri wUri = new Uri(Settings.Default.Uri);
                this.widgetHostPanel.Url = wUri;

                //http://msdn2.microsoft.com/ko-kr/library/a0746166(VS.80).aspx
                widgetHostPanel.ObjectForScripting = this;

                Settings.Default.PropertyChanged += new PropertyChangedEventHandler(Default_PropertyChanged);

                wndX = this.Left;
                wndY = this.Top;

            }
            catch (Exception exc)
            {
                MessageBox.Show("다음과 같은 이유로 위젯을 실행할수 없습니다.\n\n" + exc.Source + "\n\n" + exc.Message + "\n\n" + exc.StackTrace, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                this.Close();
            }

        }
      
        private void widgetHostPanel_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            try
            {
                HtmlDocument doc = widgetHostPanel.Document;

                doc.BackColor = Color.Magenta;  //HTML의 color key를 제작자가 지정하지 않아도 동작하게 함 1.26 - 윤제상          
                doc.ContextMenuShowing += new HtmlElementEventHandler(Document_ContextMenuShowing);
                doc.MouseDown += new HtmlElementEventHandler(doc_MouseDown);

                //this.Opacity = Settings.Default.Opacity;
            }
            catch (Exception exc)
            {
                MessageBox.Show("다음과 같은 이유로 위젯을 실행할수 없습니다.\n\n" + exc.Source + "\n\n" + exc.Message + "\n\n" + exc.StackTrace, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                this.Close();
            }
           
        }

        void doc_MouseDown(object sender, HtmlElementEventArgs e)
        {            
            m_wndSettings._Log("$$$$$$$$$$$$$$$$");

            if (e.MouseButtonsPressed == MouseButtons.Right)
            {
                m_wndSettings._Log("$$$$$$000000000");

                ctxMenuHost.Show(new Point(this.Left + e.MousePosition.X, this.Top + e.MousePosition.Y - 10));
                
                e.ReturnValue = false;                
                return;
            }
            else if(e.CtrlKeyPressed && e.MouseButtonsPressed == MouseButtons.Left)
            {  
                //창 드래그 소스
                NativeWin32.ReleaseCapture();
                NativeWin32.SendMessage(this.Handle, NativeWin32.WM_NCLBUTTONDOWN, 2, 0);               
            }

            e.ReturnValue = true;
        }


        private void widgetHostForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                //현재 위치를 저장(시작시 참고)
                Settings.Default.StartX = this.Top;
                Settings.Default.StartY = this.Left;

                m_widgetLoader.saveWidgetSettings();

                widgetHostPanel.Dispose();
            }
            catch (Exception exc)
            {
                MessageBox.Show("다음과 같은 이유로 위젯을 실행할수 없습니다.\n\n" + exc.Source + "\n\n" + exc.Message + "\n\n" + exc.StackTrace, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }


        private void Document_ContextMenuShowing(object sender, HtmlElementEventArgs e)
        {
            //for silverlight - 실버라이트에서 먹힘             
            e.ReturnValue = false;
        }

        private void openSettings_Click(object sender, EventArgs e)
        {
            m_wndSettings.ShowDialog();
        }

        private void widgetClose_Click(object sender, EventArgs e)
        {
            this.Close();           
        }
                
    }

}
